<template>
  <n-layout class="login-container bg-[#F9F9F9] dark:bg-[#101014] h-full px-5">
    <div class="h-full flex justify-center items-center space-x-16">
      <img :src="`${currentPageImagesPath}/login_bg.svg`" alt="login-bg">
      <n-card :bordered="false" class="w-[459px] h-86 p-10 rounded-lg">
        <n-form ref="loginFormRef" :model="loginState.form" :rules="loginState.rules" :show-label="false">
          <h1 class="text-center text-xl font-semibold mb-7">防红系统</h1>
          <n-form-item path="username">
            <n-input v-model:value="loginState.form.username" :disabled="loginState.loading" placeholder="请输入您的用户名"
                     size="large">
              <template #prefix>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item path="password">
            <n-input v-model:value="loginState.form.password" :disabled="loginState.loading" placeholder="请输入您的密码"
                     show-password-on="mousedown" size="large" type="password">
              <template #prefix>
              </template>
            </n-input>
          </n-form-item>
          <n-button :loading="loginState.loading" class="w-full" size="large" type="primary" @click="submitLogin">登录</n-button>
        </n-form>
      </n-card>
    </div>
  </n-layout>
</template>

<script setup>
import {reactive, getCurrentInstance} from 'vue'
import {useRouter} from 'vue-router'
import {useUserStore} from '@/store'
import {login} from '@api/userApi'

const router = useRouter()
const {proxy} = getCurrentInstance()
const userStore = useUserStore()
const currentPageImagesPath = '/images/page-images/login-images'

const loginState = reactive({
  loading: false,
  form: {
    username: 'admin@qq.com',
    password: '123456'
  },
  rules: {
    username: [
      {
        required: true,
        validator(rule, value) {
          if (!value) return new Error('请输入您的用户名')
          const mailReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
          if (!mailReg.test(value)) return new Error('请输入正确的邮箱账号')
          return true
        },
        trigger: 'input'
      },
    ],
    password: [
      {required: true, message: '请输入您的密码', trigger: 'input'}
    ]
  }
})

const submitLogin = () => {
  proxy.$refs.loginFormRef.validate(async validate => {
    if (validate) return $message.error('用户名或密码不能为空！')
    loginState.loading = true
    try {
      const res = await login(loginState.form)
      if (res?.code === 0) {
        const token = res.data.token
        userStore.setUserState(token)
        $message.success(res.msg)
        await router.replace('/center')
      }
    } finally {
      loginState.loading = false
    }
  })
}
</script>

<style lang="less" scoped>
.login-container{
  &:deep(.n-card){
    .n-card__content{
      padding-top: 0;
    }
  }
}
</style>
